import axios from 'axios'
import {
	Toast
} from 'vant';
import store from '@/store'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
	baseURL: 'http://49.235.99.41', // url = base url + request url
	// baseURL: 'http://localhost:8080',
	// baseURL:'/api',
	// baseURL:'apiTest'
	// withCredentials: true, // send cookies when cross-domain requests
	cache: false,
	timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
	config => {
		// do something before request is sent
		// console.log(config);
		if (store.getters.token) {
			// let each request carry token
			// ['X-Token'] is a custom headers key
			// please modify it according to the actual situation
			config.headers['token'] = uni.getStorageSync('token')
		}
		return config
	},
	error => {
		// do something with request error
		console.error(error) // for debug
		return Promise.reject(error)
	}
)

// response interceptor
service.interceptors.response.use(
	/**
	 * If you want to get http information such as headers or status
	 * Please return  response => response
	 */

	/**
	 * Determine the request status by custom code
	 * Here is just an example
	 * You can also judge the status by HTTP Status Code
	 */
	response => {
		if (response.code === 400 || response.code === 403 || response.code === 500) {
			// to re-login
			MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again',
				'Confirm logout', {
					confirmButtonText: 'Re-Login',
					cancelButtonText: 'Cancel',
					type: 'warning'
				}).then(() => {
				store.dispatch('user/resetToken').then(() => {
					location.reload()
				})
			})
			return Promise.reject(Toast({
				message: response.code || '服务器错误请稍后重试',
				position: 'top'
			}))
		}

		const res = response.data
		// if the custom code is not 20000, it is judged as an error.
		switch (res.status) {
			case 200:
				if (/^注意/.exec(res.msg)) {
					Toast({
						message: res.msg,
						position: 'top'
					})
				}
				return response;
			case 400:
				Toast({
					message: res.msg,
					position: 'top'
				})
				return
			case 403:
				Toast({
					message: res.msg,
					position: 'top'
				})
				uni.reLaunch({
					url:'../../pages/login/index'
				})
				return

		}
	},
	error => {
		console.error(`错误：${error.message}`) // for debug
		Toast({
			message: `错误：${error.message}`,
			position: 'top'
		})
		return Promise.reject(error)
	}
)

export default service
